//
//  SSCleanDetailSecondPartView.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/2/14.
//

import UIKit

/// 定义一个闭包
public typealias SecondPartViewResultClosure = (_ number: Int)->()

class SSCleanDetailSecondPartView: UIView {
    
    var items: [ListCombo] = []
    var lastLabMaxY:CGFloat = 0
    var numberResultClosure: SecondPartViewResultClosure?     // 闭包

    
    class func secondPartView()->SSCleanDetailSecondPartView{
        return Bundle.main.loadNibNamed("SSCleanDetailSecondPartView", owner: nil, options: nil)?.last as! SSCleanDetailSecondPartView
    }
    //xiblayout加载后
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
    @objc func clickAction(_ tap: UITapGestureRecognizer){
        let view = tap.view!
        numberResultClosure?(view.tag)
        debugPrint("\(view.tag)")
    }
    
    func numberResult(_ finished: @escaping SecondPartViewResultClosure) {
        numberResultClosure = finished
    }
    
    func setItems(items:[ListCombo]) {
        self.items = items
        
        for v in self.subviews {
            v.removeFromSuperview()
        }
        var x: CGFloat = 0
        var y: CGFloat = 0
        let width: CGFloat = 108
        let height: CGFloat = 108
        let margin:CGFloat = (self.frame.width - width * 3)/2
        var lastLabMaxY:CGFloat = 0
        for (i, item) in items.enumerated() {
            let count = i%3
            if(count == 0&&(i != 0)){
                x = 0
                y = lastLabMaxY + 16
            }
            let label = UIImageView()
            label.isUserInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(clickAction(_:)))
            label.addGestureRecognizer(tap)
//            label.backgroundColor = UIColor.red
            label.tag = i
            label.frame = CGRect(x: x, y: y, width: width, height: height)
            addSubview(label)
            x = label.frame.maxX + margin
           
            lastLabMaxY = label.frame.maxY
            print("---count\(count)")
            print("---yyy\(y)")
            label.setImage(with: item.imgUrl)
        }
        frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: lastLabMaxY)
        self.lastLabMaxY = lastLabMaxY
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: self.lastLabMaxY)
    }
    
}
